package com.example.permissionsdispatcherdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.widget.Toast;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions  // 需要动态申请权限的Activity或者Fragment，必须
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // MainActivityPermissionsDispatcher是编译后permissionsdispatcher自动生成的，这个类(Activity/Fragment)名+PermissionsDispatcher

        findViewById(R.id.button_1).setOnClickListener(v -> {
            // 调用带权限检查的方法
            MainActivityPermissionsDispatcher.getCameraPermissionWithPermissionCheck(this);
        });

        findViewById(R.id.button_2).setOnClickListener(v -> {
            // 调用带权限检查的方法
            MainActivityPermissionsDispatcher.getReadWritePermissionWithPermissionCheck(this);
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 代理权限处理到PermissionsDispatcher自动生成的方法
        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @NeedsPermission(Manifest.permission.CAMERA)  // 获取权限时调用的方法，必须
    public void getCameraPermission() {
        Toast.makeText(this, "申请相机权限成功", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)  // 权限被拒绝时触发
    public void onCameraPermissionDenied() {
        Toast.makeText(this, "申请相机权限被拒绝", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)  // 拒绝且不再询问时触发
    public void onCameraPermissionNeverAskAgain() {
        Toast.makeText(this, "申请相机权限被不再询问", Toast.LENGTH_SHORT).show();
    }

    //  @OnShowRationale，申请前，解释为什么需要这个权限

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})  // 获取权限时调用的方法，必须
    public void getReadWritePermission() {
        Toast.makeText(this, "申请读写权限成功", Toast.LENGTH_SHORT).show();
    }

    @OnPermissionDenied({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})  // 权限被拒绝时触发
    public void onReadWritePermissionDenied() {
        Toast.makeText(this, "申请读写权限被拒绝", Toast.LENGTH_SHORT).show();
    }

    @OnNeverAskAgain({Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})  // 拒绝且不再询问时触发
    public void onReadWritePermissionNeverAskAgain() {
        Toast.makeText(this, "申请读写权限被不再询问", Toast.LENGTH_SHORT).show();
    }

}